<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Config extends Model
{
    protected $table = 'config_info';
    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';
    protected $fillable = ['name','title','value','desc','type_id','value_type','options','sort'];

    public static function config(){
        $configData = Cache::get('configList');
        if(empty($configData)){
            $configData = [];
            $data = self::get()->toArray();
            foreach($data as $v){
                $configData[$v['name']] = $v['value'];
            }
        }
        $configs = json_encode($configData);
        $configData = json_decode($configs);
        return $configData;
    }

    public static function setConfig($name,$value){
        $configData = Cache::get('configList');
        if(empty($configData)){
            $configData = [];
            $configData[$name] = $value;
            Cache::forever('configList', $configData);//缓存配置信息
        }else{
            $configData[$name] = $value;
            Cache::forever('configList', $configData);//缓存配置信息
        }
    }

    public static function getConfig($name){
        $configData = Cache::get('configList');
        if(empty($configData)){
            $configData = [];
            return self::configInfo($name,$configData);
        }else{
            if(isset($configData[$name])){
                return $configData[$name];
            }else{
                return self::configInfo($name,$configData);
            }
        }
    }

    private static function configInfo($name,$configData=[]){
        $info = self::where('name',$name)->select('value')->first();
        if($info){
            $configData[$name] = $info->value;
            Cache::forever('configList', $configData);//缓存配置信息
            return $info->value;
        }else{
            return [];
        }
    }

}
